#!/bin/bash
# 中文增强版 VPS 性能测试脚本

LOGFILE="vps性能测试_$(date +%F_%H-%M-%S).log"
exec > >(tee -a "$LOGFILE") 2>&1

echo "=== VPS 性能测试脚本（中文增强版） ==="
echo "📁 日志文件已保存为：$LOGFILE"

# 检查 root 权限
if [ "$EUID" -ne 0 ]; then
    echo "❌ 请使用 root 权限运行此脚本"
    exit 1
fi

# 安装依赖
echo "📦 正在安装必要工具..."
if command -v apt &>/dev/null; then
    apt update
    apt install -y curl wget traceroute sysbench lshw iputils-ping dmidecode
elif command -v yum &>/dev/null || command -v dnf &>/dev/null; then
    yum install -y epel-release
    yum install -y curl wget traceroute python3-pip sysbench lshw iputils dmidecode
else
    echo "❌ 未识别的包管理器，请手动安装依赖"
    exit 1
fi

# 收集系统信息
OS=$(grep PRETTY_NAME /etc/os-release | cut -d= -f2 | tr -d '"')
KERNEL=$(uname -r)
ARCH=$(uname -m)
CPU_MODEL=$(lscpu | grep 'Model name' | awk -F: '{print $2}' | sed 's/^[ \t]*//')
CPU_CORES=$(nproc)
CPU_THREADS=$(lscpu | awk '/^CPU\(s\)/ {print $2}')
CPU_FREQ=$(lscpu | grep -m1 'CPU MHz' | awk '{print $NF}')
if [[ -z "$CPU_FREQ" ]]; then
    CPU_FREQ=$(grep -m1 'cpu MHz' /proc/cpuinfo | awk -F: '{print $2}' | sed 's/^[ \t]*//')
fi
CPU_FREQ=${CPU_FREQ:-未知}
MEM_TOTAL=$(free -h | grep Mem | awk '{print $2}')
MEM_FREE=$(free -h | grep Mem | awk '{print $7}')
SWAP_TOTAL=$(free -h | grep Swap | awk '{print $2}')
DISK_TOTAL=$(lsblk -b | grep disk | awk '{sum+=$4} END {printf "%.2f GB\n", sum/1024/1024/1024}')
FS_TYPE=$(df -T | grep '/$' | awk '{print $2}')

# 公网 IP 获取（优先 ipinfo.io，回退 hostname -I）
PUB_IP=$(curl -s https://ipinfo.io/ip)
if [[ -z "$PUB_IP" || "$PUB_IP" == *"html"* || "$PUB_IP" == *"Forbidden"* ]]; then
    PUB_IP=$(hostname -I | awk '{print $1}')
fi
PUB_IP=${PUB_IP:-获取失败}

GATEWAY=$(ip route | grep default | awk '{print $3}')
DNS=$(cat /etc/resolv.conf | grep nameserver | head -n1 | awk '{print $2}')
IPV6=$(ip a | grep inet6 &>/dev/null && echo 有 || echo 无)
VIRT=$(systemd-detect-virt)
CLOUD_VENDOR=$(curl -s https://ipinfo.io/org)
LOAD=$(uptime | sed 's/.*load average:/负载平均值:/')

# CPU 性能测试
CPU_SCORE=$(sysbench cpu --cpu-max-prime=20000 run | grep "events per second" | awk '{print $4}')

# 磁盘 I/O 性能测试
sysbench fileio --file-total-size=1G prepare
DISK_IO=$(sysbench fileio --file-total-size=1G --file-test-mode=seqrd run | grep "read, MiB/s" | awk '{print $3}')
sysbench fileio --file-total-size=1G cleanup

# 网络测速：Ping + 路由追踪国内搜索引擎
declare -A search_targets=(
    ["百度"]="www.baidu.com"
    ["头条搜索"]="www.toutiao.com"
    ["搜狗"]="www.sogou.com"
    ["360搜索"]="www.so.com"
    ["神马搜索"]="m.sm.cn"
    ["必应中国"]="cn.bing.com"
)

declare -A PING_RESULTS
declare -A TRACE_RESULTS

for name in "${!search_targets[@]}"; do
    host="${search_targets[$name]}"
    loss=$(ping -c 5 "$host" | grep 'packet loss' | awk -F, '{print $3}' | sed 's/ //g')
    avg=$(ping -c 5 "$host" | tail -1 | awk -F '/' '{print $5}')
    PING_RESULTS["$name"]="平均延迟 ${avg} ms，丢包率 ${loss}"

    # 路由追踪：只保留最后一条包含星号的跳
    trace_output=$(traceroute -w 2 -q 1 "$host")
    filtered_trace=""
    last_star=""
    last_star_index=""
    while IFS= read -r line; do
        if echo "$line" | grep -Eq "^[[:space:]]*[0-9]+[[:space:]]+\*"; then
            last_star="$line"
            last_star_index=$(echo "$line" | awk '{print $1}')
            continue
        fi
        filtered_trace+="$line"$'\n'
    done <<< "$trace_output"
    if [ -n "$last_star" ]; then
        filtered_trace+="$(printf "%2d  *\n" "$last_star_index")"
    fi
    TRACE_RESULTS["$name"]="$filtered_trace"
done

# 汇总输出
echo "✅ 测试完成，以下是完整汇总结果："
echo "=================================="

echo "📌 VPS 系统信息（增强版）"
echo "----------------------------------"
echo "  🧾 操作系统版本：$OS"
echo "  🧬 内核版本：$KERNEL"
echo "  🧱 系统架构：$ARCH"
echo "  🧠 CPU 型号：$CPU_MODEL"
echo "  🔢 CPU 核心数：$CPU_CORES"
echo "  🔁 CPU 线程数：$CPU_THREADS"
echo "  🚀 CPU 主频：$CPU_FREQ MHz"
echo "  🧮 内存总量：$MEM_TOTAL"
echo "  🧮 可用内存：$MEM_FREE"
echo "  🔄 Swap 空间：$SWAP_TOTAL"
echo "  💽 磁盘总容量：$DISK_TOTAL"
echo "  📂 文件系统类型：$FS_TYPE"
echo "  🌐 公网 IP：$PUB_IP"
echo "  🌐 默认网关：$GATEWAY"
echo "  🌐 DNS 服务器：$DNS"
echo "  🌐 IPv6 支持：$IPV6"
echo "  🧱 虚拟化类型：$VIRT"
echo "  ☁️ 云服务识别：$CLOUD_VENDOR"
echo "  📊 系统负载：$LOAD"

echo ""
echo "⚙️ 性能测试"
echo "----------------------------------"
echo "  🔧 CPU 每秒处理事件数：$CPU_SCORE"
echo "  💾 磁盘顺序读取速度：$DISK_IO MiB/s"

echo ""
echo "🌐 网络测试（国内搜索引擎）"
echo "----------------------------------"
for name in "${!search_targets[@]}"; do
    echo "🔎 $name（${search_targets[$name]}）"
    echo "  📶 ${PING_RESULTS[$name]}"
    echo "  📡 路由追踪（仅显示有效跳）："
    echo "${TRACE_RESULTS[$name]}"
    echo ""
done

# 清理缓存文件
echo "🧹 正在清理缓存文件..."
rm -rf *.test
rm -rf sysbench-test* test_file.* test_file.*.*
rm -rf /tmp/*speedtest* /tmp/*testfile* /tmp/*curl*

# ✅ 美化结尾输出
echo "📁 日志文件已保存：$LOGFILE"
echo "=================================="
echo -e "🎉 \033[1;32mVPS 性能测试全部完成！感谢使用！\033[0m"
echo "=================================="
